package com.soul.dubbo.api.mongo;

import com.mongodb.client.result.UpdateResult;
import com.soul.model.mongo.UserLocation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mdoya
 * @version 1.0
 * @description: 上报地址位置
 */
@Slf4j
@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 用户上报地理位置
     *
     * @param userId
     * @param longitude 经度
     * @param latitude  纬度
     * @param addrStr   用户地址
     */
    @Override
    public void reportLocation(Long userId, Double longitude, Double latitude, String addrStr) {
        // 1. 查询用户位置
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        long nowTime = System.currentTimeMillis();
        // 2. 位置存在
        if (userLocation != null){
            System.err.println("更新了");
            Update update = new Update();
            update.set("location",new GeoJsonPoint(longitude,latitude));
            update.set("address",addrStr);
            update.set("updated",nowTime);
            mongoTemplate.updateFirst(query, update,UserLocation.class);
            return;
        }
        log.debug("新增了");
        System.err.println("新增了");
        // 3. 位置不存在
        userLocation = new UserLocation();
        userLocation.setUserId(userId);
        userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
        userLocation.setAddress(addrStr);
        userLocation.setCreated(nowTime);
        userLocation.setUpdated(nowTime);
        mongoTemplate.insert(userLocation);
    }

    /**
     * 查询地址位置
     *
     * @param userId   当前用户id
     * @param distance 距离 单位：米
     * @return List<Long>
     */
    @Override
    public List<Long> searchNearBy(Long userId, Long distance) {
        // 1. 查询当前用户位置
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);

        // 2. 根据distance距离条件查询用户所在地址位置附近用户
        Query query2 = new Query();
        Circle circle = new Circle(userLocation.getLocation(),new Distance(distance/1000, Metrics.KILOMETERS));
        query2.addCriteria(Criteria.where("location").withinSphere(circle).and("userId").ne(userId));
        List<UserLocation> userLocationList = mongoTemplate.find(query2, UserLocation.class);

        // 3. 附近好友转为ids 非空返回继续完成业务
        if (!CollectionUtils.isEmpty(userLocationList)){
            return userLocationList.stream().map(UserLocation::getUserId).collect(Collectors.toList());
        }
        return null;
    }


}
